package com.example.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mall.annotation.TakeTime;
import com.example.mall.domain.dto.UserDTO;
import com.example.mall.domain.entity.User;
import com.example.mall.mapper.ImageMapper;
import com.example.mall.mapper.UserMapper;
import com.example.mall.service.UserService;
import com.example.mall.utils.TokenUtils;
import com.example.mall.domain.vo.UserVO;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private ImageMapper imageMapper;

    @TakeTime(methodName = "login")
    @Override
    public UserVO login(UserDTO userDTO) {
        // 1. 根据用户名查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, userDTO.getUsername());
        User user = this.getOne(queryWrapper);
        if(user == null){
            throw new RuntimeException("用户名或密码错误");
        }
        // 2.生成token
        String token = TokenUtils.createToken(user.getId().toString(), user.getPassword());

        // 2.1 查询用户头像的url
        String avatarUrl = imageMapper.selectById(user.getImageId()).getFilePath();

        // 3.封装数据
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setToken(token);
        userVO.setAvatarUrl(avatarUrl);

        return userVO;
    }

    @Override
    public Page<UserVO> pageUserVOList(Page<UserVO> objectPage,String name, String role) {
        return userMapper.pageUserVOList(objectPage, name, role);
    }

    @Override
    public UserVO getUserInfoById(Long id) {
        // 1.根据id获取用户的详细信息
        User user = userMapper.selectById(id);
        // 2.根据image_id获取图片的url
        String avatarUrl = imageMapper.selectById(user.getImageId()).getFilePath();

        // 3.封装
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setAvatarUrl(avatarUrl);
        return userVO;
    }
}